package com.warehouse.filter;


import com.warehouse.dao.common.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

import javax.servlet.*;
import java.io.IOException;

public class OpenSessionFilter implements Filter {
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        Session session=null;
        Transaction tr=null;
        try {
            session= HibernateUtil.currentSession();
            tr= session.beginTransaction();
            filterChain.doFilter(servletRequest,servletResponse);
            tr.commit();
        }
        catch (Exception ex)
        {
            tr.rollback();
            //log4j记录错误日志
            ex.printStackTrace();
        }
        finally{
            HibernateUtil.closeSession();
        }
    }

    public void init(FilterConfig config) throws ServletException { }
    public void destroy() { }
}
